package space.yangmin.baidu.downloader.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import space.yangmin.baidu.downloader.bo.AuthorizationInfo;
import space.yangmin.baidu.downloader.config.BaiduNetDiskConfig;
import space.yangmin.baidu.downloader.constant.CONSTANTS;
import space.yangmin.baidu.downloader.controller.base.BaseController;
import space.yangmin.baidu.downloader.mode.AuthorizationCodeMode;
import space.yangmin.baidu.downloader.util.CachePoolUtil;
import space.yangmin.baidu.downloader.util.R;

/**
 * @Description TODO
 * @Version 1.0.0
 * @Date 2024/8/5/0005 16:16
 * @Author Administrator
 */
@RestController
@RequestMapping("/authorization")
public class AuthorizationController extends BaseController {

    /**
     * 授权码获取AK
     * @param authorizationCode
     * @return
     */
    @RequestMapping
    public R authorization(@RequestParam("code") String authorizationCode){
        if(StrUtil.isBlank(authorizationCode)){
            return R.fail();
        }else{
            //初始化AK
            String accessToken = this.initAuthorizationAccessToken(authorizationCode);

            return R.ok(accessToken);
        }
    }

    /**
     * 初始化AK
     * @param authorizationCode
     */
    private String initAuthorizationAccessToken(String authorizationCode){
        String accessToken = null;
        BaiduNetDiskConfig baiduNetDiskConfig = SpringUtil.getBean(BaiduNetDiskConfig.class);
        switch (baiduNetDiskConfig.getMode()){
            //授权码
            case AUTHORIZATION_CODE:
                AuthorizationCodeMode instance = AuthorizationCodeMode.getInstance();
                AuthorizationInfo authorizationInfo = instance.getAccessToken(authorizationCode);
                CachePoolUtil.put(CONSTANTS.AUTHORIZATION_INFO, authorizationInfo);
                accessToken = authorizationInfo == null ? "" : authorizationInfo.getAccessToken();
                break;
            //简化模式
            case IMPLICIT_GRANT:
                break;
            //简化模式
            case DEVICE_CODE:
                break;
            default:
                break;
        }
        return accessToken;
    }

}
